package com.xuruzi.demo.controller;

import com.xuruzi.demo.util.ApiConfig;
import com.xuruzi.demo.util.WxUtils;
import com.xuruzi.demo.util.api.UserApi;
import com.xuruzi.demo.util.response.GetUserInfoResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

/**
 * Created by xuruzi on 2020/3/26.
 */
@Controller
public class LoginController {
    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
    @Autowired
    ApiConfig apiConfig;

    @GetMapping("/loginQrCode")
    public String loginQrCode(String code){
//        apiConfig.getAccessToken();
//        logger.info(apiConfig.getAccessToken());
        UserApi userApi = new UserApi();
        GetUserInfoResponse response = userApi.getUserInfo(code,apiConfig.getAccessToken());
        if(response != null){
            logger.info("扫码登陆用户===="+response.getUserId());
        }

        return "main";
    }

    @GetMapping("/login")
    public String login(){
        return "login";
    }

    /**
     *
     * @param redirectUrl 重定向地址
     * @param domain 政务微信后台地址
     * @return
     */
    @GetMapping("/oauthUrl")
    public String getOauthUrl(String redirectUrl,String domain) throws Exception{
        StringBuilder builder = new StringBuilder("http://");
        builder.append(WxUtils.getDomain())
                .append("/wwopen/sso/qrConnect?")
                .append("appid=").append(WxUtils.getCorpId())
                .append("&agentid=").append(WxUtils.getAgentid())
                .append("&redirect_uri=").append(WxUtils.getEncodeUrl());
        System.err.println(builder.toString());
        return "login";
    }


    public void testGetAccessToken(){
        //测试并发获取token
//        for(int i = 0 ; i < 10 ; i++){
//            new Thread(
//                    new Runnable() {
//                        @Override
//                        public void run() {
//                            for(int k=0; k < 10 ; k ++){
//                                String access_token = apiConfig.getAccessToken();
//                                System.err.println("线程名称:"+Thread.currentThread().getName()+" === access_token :"+access_token);
//                            }
//                        }
//                    }
//            ).start();
//        }
    }
}
